package cn.cloudreal.cbms.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import cn.cloudreal.cbms.vo.QueryArrangement;

public class StringUtils {

    public static List<String> tokenizeToList(String url, String token) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }

        StringTokenizer st = new StringTokenizer(url, token);
        List<String> urlList = new ArrayList<String>();
        while (st.hasMoreTokens()) {
            String item = st.nextToken().trim();
            if (item.length() > 0) {
                urlList.add(item);
            }
        }

        return urlList;
    }

    public static String clearUrl(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        int index = url.lastIndexOf("/");

        if (index == -1) {
            return url;
        }

        return url.substring(index + 1, url.length());
    }

    public static boolean isEmpty(String str) {
        if (str == null || str.trim().length() <= 0 || str.equals("null")) {
            return true;
        }

        return false;
    }

    public static int toInt(Object obj) {
        try {
            return Integer.parseInt(obj.toString());
        }
        catch (Exception ex) {
            return 0;
        }
    }

    /**
     * 将字符串时间转换成java.util.Date类型
     * 
     * @param str
     *            要转换的字符
     * @param format
     *            时间格式
     * @return 如果转换失败，返回null
     */
    public static Date string2Date(String str, String format) {
        if (isEmpty(str) || isEmpty(format)) {
            return null;
        }

        // 定义日期/时间格式
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {
            // 转换日期/时间格式
            date = sdf.parse(str);

            if (!str.equals(sdf.format(date))) {
                date = null;
            }
        }
        catch (ParseException e) {
            date = null;
        }

        return date;
    }

    public static String getMathAndTime() {
        String num = String.valueOf(Math.round(Math.random() * 1000000));
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String time = sf.format(date);// 当前时间
        return time + num;
    }

    public static String formatDateToString(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 判断某年的2月有多少天
     */
    public static int getFebruary(int year) {
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
            return 29;
        }
        return 28;
    }

    /**
     * 计算时间段相隔多少天
     */
    public static int getNumberOfDays(String arrangementStartTime, String arrangementEndTime) {
        long daysBetween = 0;
        if (!arrangementStartTime.equals("") && !arrangementEndTime.equals("")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
            try {
                Date d1 = sdf.parse(arrangementStartTime);
                Date d2 = sdf.parse(arrangementEndTime);
                daysBetween = (d2.getTime() - d1.getTime() + 1000000) / (3600 * 24 * 1000);
            }
            catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return (int) daysBetween;
    }

    public static int getDayByDate(String date) {
        int year = 0, month = 0, day = 0;
        int total = 0;
        int i;

        if (date != null && !date.equals("")) {
            year = Integer.parseInt(date.substring(0, 4));
            month = Integer.parseInt(date.substring(5, 7));
            day = Integer.parseInt(date.substring(8));
        }

        int a[] = { 31, getFebruary(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

        // System.out.println("The date you input is:" + year + " " + month +
        // " "
        // + day);

        if (month == 1) {
            total = day;
        }
        else {
            for (i = 0; i < (month - 1); i++) {
                total = total + a[i];
            }

            total = total + day;

        }
        return total;
    }

    /**
     * 计算时间段相隔多少天
     */
    public static String[] getSubArrangement(String arrangementStartTime,
            String arrangementEndTime,
            String mediumArrangement,
            int totalDays,
            QueryArrangement arrangement) {
        String[] array1 = mediumArrangement.split(",");
        String[] array2 = new String[totalDays];
        int start = Integer.valueOf(arrangement.getFactStartTime().substring(8)) - 1;
        int end = Integer.valueOf(arrangement.getFactEndTime().substring(8)) - 1;
        int start1 = Integer.valueOf(arrangementStartTime.substring(8)) - 1;
        int end1 = Integer.valueOf(arrangementEndTime.substring(8)) - 1;
        for (int i = 0; i < array2.length; i++) {
            if ((i + start1) >= start && (i + start1) <= end) {
                if (getDayByDate(arrangementStartTime) == 0) {
                    array2[i] = array1[(i + getDayByDate(arrangementStartTime))];
                }
                else {
                    array2[i] = array1[(i + getDayByDate(arrangementStartTime) - 1)];
                }
            }
            else {
                array2[i] = "--";
            }

        }
        return array2;
    }

    // 判断特殊字符，有的话true 否则没有 false
    public static Boolean StringFilter_Bool(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        // String regEx = "[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(str);
        boolean bool = matcher.find();
        return bool;
    }

    // 过滤特殊字符
    public static String StringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        // String regEx = "[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 获取字符串的长度，如果有中文，则每个中文字符计为2位
     * 
     * @param value
     *            指定的字符串
     * @return 字符串的长度
     */
    public static int getStringLength(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            }
            else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    public static boolean isChinese(String str) {
        Pattern pattern = Pattern.compile("[\\u3400-\\u9FBF]+");// 是否中文表达式
        if (str == null)
            return false;

        if (pattern.matcher(str.trim()).find())
            return true;
        else
            return false;
    }


    /**
     * @param args
     */
    public static int getMaxDayByMonth(String date) {
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(5, 7)) - 1;
        int a[] = { 31, getFebruary(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        return a[month];

    }

    public static void main(String[] args) {
        System.out.println(new StringUtils().getDayByDate("2012-08-01"));
    }

}
